package utils

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"strconv"
)

const (
	//PaperSavePath
	PaperSavePath = "/static/paper"
)

//UploadFileToServer upload file to server
func UploadFileToServer(file multipart.File, fileName string, dirPath string) (string, error) {
	// Create the file on the server
	dstPath := dirPath + fileName
	dst, err := os.Create(dstPath)
	if err != nil {
		return "", err
	}
	defer dst.Close()

	// Copy the file to the destination
	_, err = io.Copy(dst, file)
	if err != nil {
		return "", err
	}

	return dstPath, nil
}

// DownloadFile download file through url
func DownloadFile(url string, path string) error {
	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	// Create output file
	if _exist, _ := IsExist(path); _exist {
		return nil
	}
	out, err := os.Create(path)
	if err != nil {
		return err
	}
	defer out.Close()
	// copy stream
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return err
	}
	return nil
}

// RequetForFile request for file
func RequetForFile(url string) (string, error) {
	var bodyStr string
	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return bodyStr, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return bodyStr, err
	}
	bodyStr = string(body)
	return bodyStr, nil
}

// DeleteFile delete local file
func DeleteFile(path string) error {
	if _exist, _ := IsExist(path); !_exist {
		err := fmt.Errorf("文件不存在")
		return err
	}
	err := os.Remove(path)
	if err != nil {
		return err
	}
	return nil
}

// IsExist 判断文件是否存在
func IsExist(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	} else if os.IsNotExist(err) {
		return false, nil
	}
	return true, err

}

// CreateFolder 创建文件夹
func CreateFolder(dir string) error {
	if dir == "" {
		err := fmt.Errorf("文件夹名为空")
		return err
	}
	err := os.MkdirAll(dir, os.ModePerm)
	if err != nil {
		return err
	}
	return nil

}

// check the file name exist or not
func CheckFileName(fileName string) (bool, string) {
	bExist, err := IsExist(fileName)
	if err != nil {
		log.Fatal(err)
	}
	if bExist {
		i := 1
		version := strconv.Itoa(i)
		for true {
			bfExist, _ := IsExist(fileName + "_" + version)
			if !bfExist {
				fileName += "_" + version
				break
			}
			i++
			version = strconv.Itoa(i)
		}
	}
	return bExist, fileName
}
